// 定义token存储键名
const TokenKey = 'App-Token'
const TokenExpireKey = 'App-Token-Expire'

// 定义应用唯一标识，避免存储冲突
const APP_IDENTIFIER = 'cx-300t-app'
const APP_TOKEN_KEY = `${APP_IDENTIFIER}_${TokenKey}`
const APP_TOKEN_EXPIRE_KEY = `${APP_IDENTIFIER}_${TokenExpireKey}`

// 判断当前平台是否支持plus.storage
let hasPlusStorage = false

// 初始化检查plus.storage
function initPlusStorage() {
  try {
    // 在onLaunch之后plus对象才会存在，所以需要延迟检查
    hasPlusStorage = typeof plus !== 'undefined' && plus && plus.storage
    console.log('初始化plus.storage:', hasPlusStorage ? '成功' : '失败')
    return hasPlusStorage
  } catch (error) {
    console.error('检查plus.storage失败:', error)
    return false
  }
}

// 获取存储方式
function getStorageMethod() {
  // 动态检查plus.storage状态
  if (typeof plus !== 'undefined' && plus && plus.storage) {
    return 'plus'
  }
  // 其他平台使用uni.storage
  return 'uni'
}

// 获取存储的数据
function getStorageItem(key) {
  try {
    const method = getStorageMethod()
    const startTime = Date.now()
    let result
    
    if (method === 'plus') {
      result = plus.storage.getItem(key)
      console.log(`[plus.storage] 获取键${key}: ${result ? '成功' : '失败'}, 耗时: ${Date.now() - startTime}ms`)
    } else {
      result = uni.getStorageSync(key)
      console.log(`[uni.storage] 获取键${key}: ${result ? '成功' : '失败'}, 耗时: ${Date.now() - startTime}ms`)
    }
    
    return result
  } catch (error) {
    console.error(`获取存储数据(${key})失败:`, error)
    return null
  }
}

// 设置存储的数据
function setStorageItem(key, value) {
  try {
    const method = getStorageMethod()
    const startTime = Date.now()
    
    if (method === 'plus') {
      plus.storage.setItem(key, value)
      console.log(`[plus.storage] 设置键${key}: 成功, 值长度: ${value.toString().length}, 耗时: ${Date.now() - startTime}ms`)
    } else {
      uni.setStorageSync(key, value)
      console.log(`[uni.storage] 设置键${key}: 成功, 值长度: ${value.toString().length}, 耗时: ${Date.now() - startTime}ms`)
    }
    
    return true
  } catch (error) {
    console.error(`设置存储数据(${key})失败:`, error)
    return false
  }
}

// 移除存储的数据
function removeStorageItem(key) {
  try {
    const method = getStorageMethod()
    const startTime = Date.now()
    
    if (method === 'plus') {
      plus.storage.removeItem(key)
      console.log(`[plus.storage] 移除键${key}: 成功, 耗时: ${Date.now() - startTime}ms`)
    } else {
      uni.removeStorageSync(key)
      console.log(`[uni.storage] 移除键${key}: 成功, 耗时: ${Date.now() - startTime}ms`)
    }
    
    return true
  } catch (error) {
    console.error(`移除存储数据(${key})失败:`, error)
    return false
  }
}

export function getToken() {
  try {
    console.log('获取Token...')
    // 动态检查plus.storage
    initPlusStorage()
    
    const expireTime = getStorageItem(APP_TOKEN_EXPIRE_KEY)
    const currentTime = new Date().getTime()
    
    // 检查token是否过期（一个月期限）
    if (expireTime) {
      const expireMs = parseInt(expireTime)
      const timeDiff = expireMs - currentTime
      const hoursLeft = Math.floor(timeDiff / (1000 * 60 * 60))
      console.log(`Token过期检查: 当前时间=${currentTime}, 过期时间=${expireMs}, 剩余时间=${hoursLeft}小时`)
      
      if (currentTime > expireMs) {
        console.log('Token已过期，自动清理')
        removeToken()
        return null
      }
    }
    
    const token = getStorageItem(APP_TOKEN_KEY)
    console.log(`获取Token结果: ${token ? '成功' : '失败'}`)
    return token || null
  } catch (error) {
    console.error('获取token失败:', error)
    return null
  }
}

export function setToken(token) {
  try {
    console.log('设置Token...')
    // 动态检查plus.storage
    initPlusStorage()
    
    // 设置token过期时间为一个月后
    const expireTime = new Date().getTime() + (30 * 24 * 60 * 60 * 1000) // 30天的毫秒数
    
    // 先移除旧的token，确保干净的环境
    removeStorageItem(TokenExpireKey)
    removeStorageItem(TokenKey)
    
    // 使用带应用标识的键名存储
    const expireResult = setStorageItem(APP_TOKEN_EXPIRE_KEY, expireTime.toString())
    const tokenResult = setStorageItem(APP_TOKEN_KEY, token)
    
    // 验证存储是否成功
    const storedToken = getStorageItem(APP_TOKEN_KEY)
    const storedExpire = getStorageItem(APP_TOKEN_EXPIRE_KEY)
    
    if (storedToken === token && storedExpire === expireTime.toString() && expireResult && tokenResult) {
      console.log('Token存储成功，有效期至:', new Date(expireTime).toLocaleString())
      return true
    } else {
      console.error('Token存储验证失败', {
        storedTokenMatches: storedToken === token,
        storedExpireMatches: storedExpire === expireTime.toString(),
        expireResult,
        tokenResult
      })
      return false
    }
  } catch (error) {
    console.error('存储token失败:', error)
    return false
  }
}

export function removeToken() {
  try {
    console.log('移除Token...')
    
    // 同时清理旧的和新的键名，确保完全清除
    const result1 = removeStorageItem(TokenExpireKey)
    const result2 = removeStorageItem(TokenKey)
    const result3 = removeStorageItem(APP_TOKEN_EXPIRE_KEY)
    const result4 = removeStorageItem(APP_TOKEN_KEY)
    
    console.log('Token移除结果:', { result1, result2, result3, result4 })
    return result1 && result2 && result3 && result4
  } catch (error) {
    console.error('移除token失败:', error)
    return false
  }
}

// 调试函数：检查存储状态
export function checkStorageStatus() {
  try {
    // 动态检查plus.storage
    initPlusStorage()
    
    const method = getStorageMethod()
    // 同时检查新旧键名的token
    const oldToken = getStorageItem(TokenKey)
    const newToken = getStorageItem(APP_TOKEN_KEY)
    const oldExpire = getStorageItem(TokenExpireKey)
    const newExpire = getStorageItem(APP_TOKEN_EXPIRE_KEY)
    
    const currentTime = new Date().getTime()
    const token = newToken || oldToken
    const expireTime = newExpire || oldExpire
    const isExpired = expireTime ? currentTime > parseInt(expireTime) : false
    
    console.log('\n=== Token存储状态检查 ===')
    console.log('平台:', process.env.NODE_ENV || 'unknown')
    console.log('存储方式:', method === 'plus' ? 'plus.storage' : 'uni.storage')
    console.log('plus.storage可用:', typeof plus !== 'undefined' && plus && plus.storage)
    console.log('当前时间:', new Date().toLocaleString())
    console.log('---')
    console.log('旧键名Token存在:', !!oldToken)
    console.log('新键名Token存在:', !!newToken)
    console.log('Token总计存在:', !!token)
    console.log('---')
    console.log('旧键名过期时间:', oldExpire ? new Date(parseInt(oldExpire)).toLocaleString() : '无')
    console.log('新键名过期时间:', newExpire ? new Date(parseInt(newExpire)).toLocaleString() : '无')
    
    if (expireTime) {
      const expireMs = parseInt(expireTime)
      const timeDiff = expireMs - currentTime
      const hoursLeft = Math.floor(timeDiff / (1000 * 60 * 60))
      console.log('Token是否过期:', isExpired)
      console.log('Token剩余有效时间:', hoursLeft + '小时')
    }
    
    // 如果发现旧键名有token而新键名没有，自动迁移
    if (oldToken && !newToken) {
      console.log('发现旧键名Token，尝试自动迁移...')
      const migrationResult = setToken(oldToken)
      console.log('Token迁移结果:', migrationResult ? '成功' : '失败')
    }
    
    return {
      platform: process.env.NODE_ENV || 'unknown',
      method: method,
      plusAvailable: typeof plus !== 'undefined' && plus && plus.storage,
      currentTime: currentTime,
      hasOldToken: !!oldToken,
      hasNewToken: !!newToken,
      hasToken: !!token,
      oldExpireTime: oldExpire,
      newExpireTime: newExpire,
      expireTime: expireTime,
      isExpired: isExpired
    }
  } catch (error) {
    console.error('检查存储状态失败:', error)
    return {
      platform: 'unknown',
      method: 'unknown',
      plusAvailable: false,
      currentTime: new Date().getTime(),
      hasOldToken: false,
      hasNewToken: false,
      hasToken: false,
      oldExpireTime: null,
      newExpireTime: null,
      expireTime: null,
      isExpired: true
    }
  }
}
